package com.kaiwukj.android.mcas.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.StringRes;

import com.kaiwukj.android.mcas.R;


public final class UToast {

    private Toast mToast;
    private static final Handler handler = new Handler(Looper.getMainLooper());

    public UToast() {
    }

    @SuppressLint("ShowToast")
    public UToast(Context context, CharSequence text, int duration) {
        mToast = Toast.makeText(context.getApplicationContext(), text, duration);
        mToast.setGravity(Gravity.CENTER, 0, 0);
        //mToast.setDuration(duration);
        //mToast.setText(text);
    }

    /**
     * 设置默认样式
     */
    private void setDefaultView() {
        View view = mToast.getView();
        if (view != null) {
            TextView textView = view.findViewById(android.R.id.message);
            view.setBackgroundResource(R.drawable.shape_bg_toast);
            textView.setTextColor(Color.WHITE);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        }
    }

    /**
     * 构建显示参数
     *
     * @param context  context
     * @param msg      message
     * @param duration duration
     * @return UToast
     */
    private static UToast commonToast(Context context, CharSequence msg, int duration) {
        UToast uToast = new UToast(context, msg, duration);
        uToast.setDefaultView();
        return uToast;
    }


    public static void showShort(Context context, String msg) {
        commonToast(context, msg, Toast.LENGTH_SHORT).show();
    }

    public static void showShort(Context context, @StringRes int strId) {
        showShort(context, context.getString(strId));
    }

    public static void showLong(Context context, String msg) {
        commonToast(context, msg, Toast.LENGTH_LONG).show();
    }

    public static void showLong(Context context, @StringRes int strId) {
        showLong(context, context.getString(strId));
    }

    private void show() {
        handler.post(() -> {
            //cancel();
            mToast.show();
        });
    }

    private void cancel() {
        mToast.cancel();
    }

}
